package com.pig4cloud.pig.ads.service.bd.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.dev2.api.sdk.campaignfeed.api.CampaignFeedService;
import com.baidu.dev2.api.sdk.campaignfeed.model.*;
import com.baidu.dev2.api.sdk.common.ApiErrorInfo;
import com.baidu.dev2.api.sdk.common.ApiRequestHeader;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.sdk.client.DyKsClient;
import com.dy.sdk.model.request.ks.KsUpdateDayBudgetRequest;
import com.dy.sdk.model.response.ks.KsResponse;
import com.google.common.collect.Lists;
import com.pig4cloud.pig.ads.pig.mapper.PlatformJobInfoMapper;
import com.pig4cloud.pig.ads.pig.mapper.bd.BdCampaignMapper;
import com.pig4cloud.pig.ads.service.AdvertiserService;
import com.pig4cloud.pig.ads.service.bd.BdCampaignService;
import com.pig4cloud.pig.ads.utils.CronUtils;
import com.pig4cloud.pig.api.entity.AccountToken;
import com.pig4cloud.pig.api.entity.PlatformJobInfo;
import com.pig4cloud.pig.api.entity.bd.BdAdgroup;
import com.pig4cloud.pig.api.entity.bd.BdAdgroupReq;
import com.pig4cloud.pig.api.entity.bd.BdCampaign;
import com.pig4cloud.pig.api.entity.ks.KsPlanReq;
import com.pig4cloud.pig.api.entity.ks.KsUnit;
import com.pig4cloud.pig.api.enums.StatusEnum;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.util.DateUtil;
import com.pig4cloud.pig.common.core.util.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author chengang
 * @Date 2022/12/21
 */
@Service
@Log4j2
@RequiredArgsConstructor
public class BdCampaignServiceImpl extends ServiceImpl<BdCampaignMapper, BdCampaign>  implements BdCampaignService {

    @Autowired
    private BdCampaignMapper bdCampaignMapper;

	private final AdvertiserService advertiserService;

	private final PlatformJobInfoMapper platformJobInfoMapper;

   @Override
   public void saveUpdateList(List<BdCampaign> list){
       List<Long> campaignIds = list.stream().map(BdCampaign::getCampaignFeedId).collect(Collectors.toList());
       if(CollectionUtils.isEmpty(campaignIds)){
           return;
       }
       List<BdCampaign> campaignList = bdCampaignMapper.getListByCampaignIds(campaignIds);
       list.forEach(a-> campaignList.forEach(c->{
               if (c.getCampaignFeedId().equals(a.getCampaignFeedId())) {
                   a.setId(c.getId());
                   a.setSoucreStatus(c.getSoucreStatus());
               }
           }));
       this.saveOrUpdateBatch(list,1000);

   }


	/**
	 * 广告计划修改预算
	 * @param req
	 * @return
	 */
	@Override
	public R updateDayBudget(BdAdgroupReq req) {
		ApiRequestHeader header = new ApiRequestHeader();
		try {
			AccountToken bdAccountToken = advertiserService.getAdvertiserToken(PlatformTypeEnum.BD.getValue(),req.getAdvertiserId().toString());
			if (Objects.isNull(bdAccountToken)) {
				return R.failed("此广告账户Token已失效");
			}
			BdCampaign bdCampaign = baseMapper.getByAdgroupFeedId(req.getAdgroupFeedId());
			if (Objects.isNull(bdCampaign)) {
				return R.failed("当前广告计划不存在 !");
			}
			BigDecimal budget = req.getBudget();
			//广告组单日预算金额，指定 0 表示预算不限，默认为 0；不小于 50元，不超过 10000000 元，仅支持输入数字;
			Boolean flag = budget.compareTo(new BigDecimal(50)) < 0 || budget.compareTo(new BigDecimal(10000000)) > 0;
			if(0 == budget.intValue()){
				flag=false;
			}
			if (flag) {
				return R.failed("修改预算值范围要在:不小于 50 元，不超过 10000000 元");
			}
			//将预算值由单位元转换成单位厘
			double budgetDouble = budget.doubleValue();

			//1 修改日预算  2 定时修改日预算
			if (StatusEnum.TYPE_ONE.getStatus().equals(req.getType())) {
				CampaignFeedService campaignFeedService = new CampaignFeedService();
				UpdateCampaignFeedRequestWrapper wrapper = new UpdateCampaignFeedRequestWrapper();
				header.setAccessToken(bdAccountToken.getAccessToken());
				//注意这里传用户名，不是用户ID
				header.setUserName(bdAccountToken.getAdvertiserName());
				wrapper.setHeader(header);
				UpdateCampaignFeedRequestWrapperBody body = new UpdateCampaignFeedRequestWrapperBody();
				List<CampaignFeedType> list = new ArrayList<>();
				CampaignFeedType updateCampaign = new CampaignFeedType();
				list.add(updateCampaign.campaignFeedId(bdCampaign.getCampaignFeedId()).budget(budgetDouble));
				body.setCampaignFeedTypes(list);
				wrapper.body(body);
				UpdateCampaignFeedResponseWrapper responseWrapper = campaignFeedService.updateCampaignFeed(wrapper);
				if (StringUtils.equals(responseWrapper.getHeader().getDesc(), "success")) {
					bdCampaign.setBudget(req.getBudget());
					//修改数据表:ks_unit的出价信息
					this.baseMapper.updateById(bdCampaign);
					return R.ok(">>>>>>百度修改广告计划预算成功");
				} else {
					List<String> mg = responseWrapper.getHeader().getFailures().stream().map(ApiErrorInfo::getMessage).collect(Collectors.toList());
					log.error(">>>>>>百度修改广告计划预算异常：" +  JSON.toJSONString(responseWrapper));
					return R.failed(JSON.toJSONString(mg));
				}
			} else {
				String jobName = "修改快手广告计划预算";
				Integer operate = StatusEnum.OPERATE_TYPE_SIX.getStatus();
				try {
					//第二天凌晨执行
					Date exeTime = DateUtil.timeToBeginDay(DateUtil.getDate(new Date(), 1));
					String cronDate = CronUtils.getCron(exeTime);
					String exeParam = JSONObject.toJSONString(req);
					List<PlatformJobInfo> platformJobInfoList = platformJobInfoMapper.selectList(Wrappers.<PlatformJobInfo>query().lambda().eq(PlatformJobInfo::getUniqueId, bdCampaign.getCampaignFeedId()).eq(PlatformJobInfo::getOperateType, operate).eq(PlatformJobInfo::getType, StatusEnum.AD_TYPE_FOUR.getStatus()).gt(PlatformJobInfo::getExecuteTime, new Date()));
					if (CollectionUtils.isEmpty(platformJobInfoList)) {
						//新增  -- 已经执行的以新增为标准，未执行以修改为准
						platformJobInfoMapper.insert(new PlatformJobInfo(bdCampaign.getCampaignFeedId(), jobName, cronDate, exeTime, exeParam, StatusEnum.JOB_STATUS_ONE.getStatus(), operate, StatusEnum.AD_TYPE_FOUR.getStatus()));
					} else {
						//修改账号修改任务-----如果还没有执行
						platformJobInfoMapper.updateById(new PlatformJobInfo(bdCampaign.getCampaignFeedId(), exeParam, cronDate, exeTime, StatusEnum.JOB_STATUS_ONE.getStatus(), platformJobInfoList.get(0).getId()));
					}
				} catch (Exception e) {
					log.error("budgetUpdate  cron  is error:", e);
					return R.failed("定时修改快手日预算异常，请稍后重试");
				}
				return R.ok();
			}

		} catch (Exception e) {
			log.error("budgetUpdate is error", e);
			return R.failed("修改预算异常" + e.getMessage());
		}
	}

}
